﻿using System;
using System.Collections.Generic;

using Argos.Collections;

namespace Argos.Scheduling
{
	/// <summary>
	/// A list of time slots.
	/// </summary>
	/// <remarks>
	/// This list does not allow duplicate time slots.
	/// </remarks>
	[Serializable]
	public sealed class TimeSlotList : UniqueList<TimeSlot>
	{

		public TimeSlotList() { }

		public TimeSlotList(IEnumerable<TimeSlot> collection) : base(collection) { }



		/// <summary>
		/// Returns the next time slot from the list that starts after the given time of day.
		/// </summary>
		/// <param name="after">The time of day to return the next starting time slot from.</param>
		public TimeSlot GetNextTimeSlot(TimeOfDay after)
		{
			if (this.Count == 0)
			{
				throw new InvalidOperationException("This method cannot be invoked on an empty list.");
			}

			List<TimeSlot> list = new List<TimeSlot>(this);
			list.Sort();
			bool found = false;

			Predicate<TimeSlot> finder = delegate(TimeSlot slot)
			{
				if(slot.Start > after)
				{
					found = true;
					return true;
				}
				return false;
			};

			TimeSlot next = list.Find(finder);
			if (!found)
			{
				next = list[0];
			}

			return next;
		}

		/// <summary>
		/// Returns the previous time slot from the list that starts before the given time of day.
		/// </summary>
		/// <param name="before">The time of day to return the previous starting time slot from.</param>
		public TimeSlot GetPreviousTimeSlot(TimeOfDay before)
		{
			if (this.Count == 0)
			{
				throw new InvalidOperationException("This method cannot be invoked on an empty list.");
			}

			return new TimeSlot();
		}

		#region public override string ToString()

		/// <summary>
		/// Returns the string representation of the time slot list.
		/// </summary>
		public override string ToString()
		{
			if (this.Count < 10)
			{
				List<string> list = new List<string>();
				foreach (TimeSlot slot in this)
				{
					list.Add(slot.ToString());
				}

				return string.Join(", ", list.ToArray());
			}
			else
			{
				return string.Format("{0} time slots", this.Count);
			}

		}

		#endregion

	}
}
